                                                                                        //
//  homeViewController.m
//  ziLu_ios
//
//  Created by mac on 16/2/2.
//  Copyright (c) 2016年 mac. All rights reserved.
//

#import "homeViewController.h"
#import "DDMenuController.h"
#import "YRSideViewController.h"
#import "AppDelegate.h"
#import <MAMapKit/MAMapKit.h>
#import "listViewController.h"
#import "UIImage+orghtimage.h"
//#import <AMapFoundationKit/AMapFoundationKit.h>
#import "CACustomAnnotationView.h"
#import "homeNextViewController.h"
#import "MJExtension.h"
#import "BubbleModel.h"
#import "AFNetworking.h"


#import "MapPinsModel.h"
#import "PartitionColor.h"
#import "RestaurantViewController.h"
#import "MedicalViewController.h"
#import "UIImage+orghtimage.h"
#import "CAPersonalInformationVC.h"
#import "CALoginViewController.h"
#import "AlertView.h"
#import "UseAgreementVC.h"
#import "CAPersonalBusinessViewController.h"
#import "RAYNewFunctionGuideVC.h"
#import "CHRollViewLabel.h"
#import "WeatherModel.h"
#import "CoreNewFeatureVC.h"


#define kCalloutViewMargin          -8

@interface homeViewController ()<MAMapViewDelegate,AMapLocationManagerDelegate,AMapSearchDelegate>
{
    MAMapView *_mapView;
    UIButton *_locationButton;
    YRSideViewController *menuctrl;
    UIView *view;
    UIBlurEffect *blur;
    UIVisualEffectView *effectview;
    LogInModel *  loginmodel;
    NSArray *arr_id;
    AMapSearchAPI *_search;
    CLLocation *_currentLocation;
    
    NSMutableArray *_cityAry;//分区字典
    
    CGFloat screeningH;//筛选的高度
    UIView *screeningView;//筛选View
    CHRollViewLabel *rollViewLabel;//滚动条
    WeatherModel *weatherModel;
    
}

@property (nonatomic, strong) UIImageView *question;

@property(nonatomic,strong) NSMutableArray *datarr;//大头针数组

@property(nonatomic, strong) UIView *questView;//右边栏问号提示框

@property (nonatomic, strong) MapPinsModel *model;//大头针
@property (nonatomic, strong) PartitionColor *colorModel;//分区颜色

@property (nonatomic, strong) NSMutableArray *partitionColorAry;//分区颜色model

@property (nonatomic, strong) NSMutableArray *overlayArray;//颜色分区数组

@property(nonatomic,copy)NSString*ID;
@property(nonatomic,copy)NSString*IDname;

@end

@implementation homeViewController

#pragma mark -- 懒加载

- (NSMutableArray *)partitionColorAry{
    if(_partitionColorAry == nil){
        _partitionColorAry = [NSMutableArray new];
        [self initCityDic];//初始化分区字典
    }
    return _partitionColorAry;
}

#pragma mark -- 界面将要显示
-(void)viewDidAppear:(BOOL)animated{
//    //    这个有个字体，先添加info.plist  然后添加paths在taget里面
//    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
//    NSString *firstComeInTeacherDetail = @"isFirstEnterHere";
//    [user setBool:NO forKey:firstComeInTeacherDetail];
//    
//    if (![user boolForKey:firstComeInTeacherDetail]) {
//        [user setBool:YES forKey:firstComeInTeacherDetail];
//        [user synchronize];
//        [self makeGuideView];
//    }
    
    [super viewDidAppear:animated];
    
    if (weatherModel != nil) {
        
        [self initRollText];//初始化 滚动框//让滚动条滚
      
    }
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self getMapPinsInfo];
        [self getPartitionColor];
    });
}


#pragma mark -- 用户引导
- (void)makeGuideView{
//    (MAIN_WIDTH - 40, MAIN_HEIGHT - 44 - 280, 30, 180)
    RAYNewFunctionGuideVC *vc = [[RAYNewFunctionGuideVC alloc]init];
    vc.titles = @[@"少侠，点我就传授你空气（质量）秘籍",
                  @"AQI是空气质量指数的简称，数值越大，污染状况越重",
                  @"优：吸氧大师",
                  @"良：清新正太",
                  @"轻度污染：惜命宅男",
                  @"严重污染：口罩忍者",
                  @"重度污染：雾都骑士",
                  @"严重污染：爆表英雄",
                  @"商务信息（商家）",
                  @"空气地图 - 全城空气，尽在我手\n商家 - SHOPPING时也要让雾霾走开\n个人用户 - 晒出一片蓝，看看其他臭美的小伙伴\n监测点 - 重型堡垒不想说话，并且想你扔出了一堆数据"];
    
    int i = 0;
    vc.frames = @[[NSString stringWithFormat:@"{{%.2f,  %.2f},{%.2f,%.2f}}",MAIN_WIDTH - 40, MAIN_HEIGHT - 44 - 280 + 64, 35.0, 190.0],
                  [NSString stringWithFormat:@"{{%.2f,  %.2f},{%.2f,%.2f}}",self.questView.x - 15, self.questView.y + 44, self.questView.width * 0.75, self.questView.height],
                  [NSString stringWithFormat:@"{{%.2f,  %.2f},{%.2f,%.2f}}",self.questView.x - 15, self.questView.y  + 94 + (self.questView.height / 6 * i++), self.questView.width * 0.8, self.questView.height / 6],
                  [NSString stringWithFormat:@"{{%.2f,  %.2f},{%.2f,%.2f}}",self.questView.x - 15, self.questView.y  + 84 + (self.questView.height / 6 * i++), self.questView.width * 0.8, self.questView.height / 6],
                  [NSString stringWithFormat:@"{{%.2f,  %.2f},{%.2f,%.2f}}",self.questView.x - 15, self.questView.y  + 75 + (self.questView.height / 6 * i++), self.questView.width * 0.8, self.questView.height / 6],
                  [NSString stringWithFormat:@"{{%.2f,  %.2f},{%.2f,%.2f}}",self.questView.x - 15, self.questView.y  + 65 + (self.questView.height / 6 * i++), self.questView.width * 0.8, self.questView.height / 6],
                  [NSString stringWithFormat:@"{{%.2f,  %.2f},{%.2f,%.2f}}",self.questView.x - 15, self.questView.y  + 60 + (self.questView.height / 6 * i++), self.questView.width * 0.8, self.questView.height / 6],
                  [NSString stringWithFormat:@"{{%.2f,  %.2f},{%.2f,%.2f}}",self.questView.x - 15, self.questView.y  + 54 + (self.questView.height / 6 * i++), self.questView.width * 0.8, self.questView.height / 6],
                  [NSString stringWithFormat:@"{{%.2f,  %.2f},{%.2f,%.2f}}",MAIN_WIDTH - 50, 20.0, 40.0, 40.0],
                  [NSString stringWithFormat:@"{{%.2f,  %.2f},{%.2f,%.2f}}",screeningView.x, screeningView.y + 60, screeningView.width + 10, 160.0]
                  ];
    vc.FGBlock = ^(NSString *text){
        if ([text isEqualToString:@"少侠，点我就传授你空气（质量）秘籍"]) {
            [self addQuestView];
        }else if ([text isEqualToString:@"严重污染：爆表英雄"]){
            [self addQuestView];
        }else if([text isEqualToString:@"商务信息（商家）"]){
            [self screening];
        
        }else if ([text isEqualToString:@"空气地图 - 全城空气，尽在我手\n商家 - SHOPPING时也要让雾霾走开\n个人用户 - 晒出一片蓝，看看其他臭美的小伙伴\n监测点 - 重型堡垒不想说话，并且想你扔出了一堆数据"]){
            [self screening];
        }
    };
    
    [self presentViewController:vc animated:YES completion:nil];
    
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [rollViewLabel removeFromSuperview];
    rollViewLabel = nil;
   
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    [AMapSearchServices sharedServices].apiKey = gaodeAppKey;
//    
////    //配置用户Key
//    [MAMapServices sharedServices].apiKey = gaodeAppKey;
 
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(next:) name:@"next" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushMyInfo) name:@"pushMyInfo" object:nil];

     menuctrl=[[YRSideViewController alloc]init];
    
    //标题
     self.titlelabel.text=@"空气地图";
    
    //左侧打开抽屉按钮
    // 设置切换到左侧个人界面按钮
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 15, 18, 18)];
    [leftButton addTarget:self action:@selector(chouTi) forControlEvents:UIControlEventTouchUpInside];
    [leftButton setBackgroundImage:[UIImage imageNamed:@"navbtn.png"] forState:UIControlStateNormal];
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    
    // 设置切换到左侧个人界面按钮
    UIButton *rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 19, 26, 26)];
    [rightButton addTarget:self action:@selector(screening) forControlEvents:UIControlEventTouchUpInside];
    [rightButton setBackgroundImage:[UIImage imageNamed:@"筛选.png"] forState:UIControlStateNormal];
    UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
    
    [self initMap];//初始化地图
    
//    [self initRollText];//初始化 滚动框//让滚动条滚
    
    [self initScreeningView];//初始化筛选view
    
    //给Viewcontroller添加移除颜色说明方法
    [self addGestureRecognizer];
    //设置分区颜色
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
//        [self divideTheArea];
//         [self getMapPinsInfo];
        [self initColorArticle];
        
    });
    
    //是否显示 用户引导
    
    if ([LoginSingleton sharedLoginSingleton].isFirstStart) {
        [self makeGuideView];
    }
}

#pragma mark -- 初始化地图
- (void)initMap{
    

    
    //初始化检索对象
    _search = [[AMapSearchAPI alloc] init];
    _search.delegate = self; 
    
    _mapView = [[MAMapView alloc] initWithFrame:self.view.bounds];
    _mapView.delegate = self;
    _mapView.showsUserLocation = YES;    //YES 为打开定位，NO为关闭定位
    //    _mapView.showsCompass =YES;  //罗盘
    _mapView.showsScale =YES;  //比例尺
    
    [_mapView setUserTrackingMode: MAUserTrackingModeFollow animated:YES]; //定位模式
    [self initControls];//自定义坐标按钮
    
    //缩放比例
    _mapView.zoomLevel = 10.2;
    
    [self.view addSubview:_mapView];
    
    
    //单次定位
    self.locationManager = [[AMapLocationManager alloc] init];
    self.locationManager.delegate = self;
    // 带逆地理信息的一次定位（返回坐标和地址信息）
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    
}

#pragma mark -- 初始化滚动字幕
- (void)initRollText{
    
    if (weatherModel == nil) {
        return;
    }
    
    if(rollViewLabel != nil)
        return;
    
    NSString *rollText = weatherModel.msg;
    
    rollViewLabel = [[CHRollViewLabel alloc] initWithFrame:(CGRectMake(0, 0, MAIN_WIDTH, 20)) text:rollText textColor:[UIColor whiteColor] textFont:13];
    [self.view insertSubview:rollViewLabel atIndex:1];
    
}

#pragma mark -- 跳转我的信息页面
- (void)pushMyInfo{
    
    [menuctrl hideSideViewController:YES];
    
    if ([[LoginSingleton sharedLoginSingleton].token isEqualToString:@""] || [LoginSingleton sharedLoginSingleton].token == nil) {
        
       __weak __typeof(self) weakSelf = self;
        
        AlertView *login = [[AlertView alloc] initWithTitle:@"登录" contentText:@"你好" ButtonTitle:@"我靠" userAgreement:^{
            
            UseAgreementVC *agreementVC = [[UseAgreementVC alloc] init];
            weakSelf.hidesBottomBarWhenPushed = YES;
            
            [weakSelf.navigationController pushViewController:agreementVC animated:YES];
            
            weakSelf.hidesBottomBarWhenPushed = NO;
            
        }];
        login.Controller = self.navigationController;
        login.tabba = (FatherBarController *)self.tabBarController;
        
        //    login.frame = CGRectMake((CGRectGetWidth(self.view.bounds) - kAlertWidth) * 0.5, - kAlertHeight - 30, MAIN_WIDTH-MAIN_WIDTH*0.09*2, kAlertHeight);
        //    [self.view addSubview:login];
        //
        login.loginBlock = ^(NSString *response,NSString *loginType){
            
            if ([loginType isEqualToString:@"1"]) {
                
                CALoginViewController *login = [[CALoginViewController alloc] init];
                
                login.loginBlock = ^(NSString *usid,NSString *loginType){
                    
                    if (![loginType isEqualToString:@"1"]) {
                        
                        [weakSelf thirdPartLoginWithInfo:usid withType:loginType];
                    }
                    
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                };
                
                weakSelf.hidesBottomBarWhenPushed = YES;
                [weakSelf.navigationController pushViewController:login animated:YES];
                
                weakSelf.hidesBottomBarWhenPushed = NO;
                
            }else{
                
                [weakSelf thirdPartLoginWithInfo:response withType:loginType];
                
            }
            
        };
        
        login.registerBlock = ^{
            
            CAPersonalBusinessViewController *registerVC = [[CAPersonalBusinessViewController alloc] init];
            weakSelf.hidesBottomBarWhenPushed = YES;
            [weakSelf.navigationController pushViewController:registerVC animated:YES];
            weakSelf.hidesBottomBarWhenPushed = NO;
            
        };
        
        [login show];

        
        
    } else{
        
        
        __weak __typeof(self) weakSelf = self;
        //        如果个人信息没有，那就获取信息
        if ([LoginSingleton sharedLoginSingleton].perInfoModel == nil) {
            
            [[LoginSingleton sharedLoginSingleton] getPerserInfoWithsuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
                
                UIStoryboard *personalInfo = [UIStoryboard storyboardWithName:@"PersonalInfomation" bundle:nil];
                
                weakSelf.hidesBottomBarWhenPushed = YES;
                [weakSelf.navigationController pushViewController:[personalInfo instantiateInitialViewController] animated:YES];
                weakSelf.hidesBottomBarWhenPushed = NO;
                
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                
            }];
            
        }else{
            
            UIStoryboard *personalInfo = [UIStoryboard storyboardWithName:@"PersonalInfomation" bundle:nil];
            
            self.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:[personalInfo instantiateInitialViewController] animated:YES];
            self.hidesBottomBarWhenPushed = NO;
        }
        
        
//        CAPersonalInformationVC *infoVC = [[CAPersonalInformationVC alloc] init];
//        
//        self.hidesBottomBarWhenPushed = YES;
//        
//        [self.navigationController pushViewController:infoVC animated:YES];
//        
//        self.hidesBottomBarWhenPushed = NO;
    }
    
    
}


#pragma mark -- 三方登录
- (void)thirdPartLoginWithInfo:(NSString *)response withType:(NSString *)loginType{
    
    [self showIndicator:@"正在处理..."];
    
    __typeof(self) weakSelf = self;
    [HTTPManager post:GET_URLString(@"Api/Member/oauth_login") parameters:@{@"type":loginType,@"phone":@"2",@"value":response} success:^(AFHTTPRequestOperation *operation, id responseObject){
        
        [weakSelf hideIndicator]; 
        
        if ([responseObject[@"msg"] isEqualToString:@"成功"]) {
            
            [ShowMessage showCenterViewMessage:@"登录成功"];
            
            //保存本地
            [[LoginSingleton sharedLoginSingleton] loginSuccess:responseObject];
            
        }else{
            [ShowMessage showCenterViewMessage:responseObject[@"msg"]];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [weakSelf hideIndicator];
        
    }];
    
}

#pragma mark -- 抽屉效果 & 筛选
-(void)chouTi{
    //_mapView.zoomEnabled = NO;
    _mapView.scrollEnabled = NO;
    
    AppDelegate *delegate=(AppDelegate*)[[UIApplication sharedApplication]delegate];
    menuctrl=[delegate sideViewController];
    menuctrl.mapView =_mapView;
    menuctrl.controller =self;
    [menuctrl showLeftViewController:YES];
    [menuctrl setNeedSwipeShowMenu:YES];
    
}

- (void)screening{
    if (screeningH == 0) {
        screeningH = 150;
    }else{
        screeningH = 0;
    }
    
    [UIView animateWithDuration:0.2 animations:^{
        screeningView.height = screeningH;
    }];
}

- (void)initScreeningView{
     screeningH = 0;//设置筛选view高度为0
    
    CGFloat viewW = 130;
    
    CGFloat viewX = MAIN_WIDTH - viewW - 5;
    CGFloat viewY = 3;
    
    screeningView = [[UIView alloc] initWithFrame:(CGRectMake(viewX, viewY, viewW, 0))];
    screeningView.backgroundColor = [UIColor colorWithPatternImage: [UIImage imageNamed:@"筛选多边形.png"]];
    
    for (int i = 0; i < 4; i++) {
        
        CGFloat btnH = 150 * 0.25;
        CGFloat btnY = btnH * i;
        
        UIButton *btn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        btn.frame = CGRectMake(0, btnY, viewW, btnH);
        [btn setTitle:@"" forState:(UIControlStateNormal)];
        [btn addTarget:self action:@selector(screeningAnnotation:) forControlEvents:(UIControlEventTouchUpInside)];
//        [btn setBackgroundColor:[UIColor redColor]];
        btn.tag = i;
        [screeningView addSubview:btn];
        
    }
    
    [self.view addSubview:screeningView];
    
}

- (void)screeningAnnotation:(UIButton *)aBtn{
    
    [self screening];
    
    switch (aBtn.tag) {
        case 0:
            
            [self initMApointAnnotation:TYPE_ALL];
            break;
        case 1:
            
            [self initMApointAnnotation:TYPE_ENTERPRISE];
            break;
        case 2:
            
            [self initMApointAnnotation:TYPE_PERSONAL];
            break;
        case 3:
            
            [self initMApointAnnotation:TYPE_DETECTION_POINT];
            break;
        default:
            break;
    } 
    
}

#pragma mark ******************** 大头针

#pragma mark -- 添加大头针(有筛选功能)
- (void)initMApointAnnotation:(AnnotationViewTypes)aType{
    
    [_mapView removeAnnotations:self.datarr];
    [self.datarr removeAllObjects];
    
    for (int i = 0; i < self.model.date.count; i++) {
        
        Infos *info = self.model.date[i];
//        如果不是aType类型的 点就不显示
        if (aType != TYPE_ALL) {
            if (info.annotationType != aType) {
                continue;
            }
        }
        
        MAPointAnnotation *po = [[MAPointAnnotation alloc] init];
        po.coordinate = CLLocationCoordinate2DMake(info.latitude.doubleValue, info.longitude.doubleValue);
        po.title = [NSString stringWithFormat:@"%d",i];
        [self.datarr addObject:po];
        
    }
    
//    dispatch_async(dispatch_get_main_queue(), ^{
//    先移除在添加
    
        [_mapView addAnnotations:self.datarr];
        
//    });
}

// 大头针协议代理方法
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *pointReuseIndentifier = @"pointReuseIndentifier";
        CACustomAnnotationView *annotationView = (CACustomAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
        if ( annotationView == nil)
        {
            annotationView = [[CACustomAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifier];
            
            annotationView.canShowCallout = NO;
            annotationView.draggable = YES;
            annotationView.centerOffset = CGPointMake(0, -5);//设置气泡可以弹出，默认为NO
        }
        
        annotationView.info = self.model.date[[annotation title].intValue];
        
        __weak __typeof(self) weakSelf = self;
        annotationView.calloutViewBlock = ^(Infos *info){
            [weakSelf next:info];
        };
        
        return  annotationView;
    }
    
    return nil;
}


#pragma mark -- 点击气泡时候跳转
-(void)next:(Infos *)info{


    switch (info.jumpType) {
        case JUMP_FOOD:{
            RestaurantViewController *VC = [[RestaurantViewController alloc] init];
            VC.urlId = info.ids;
            self.navigationController.navigationBar.hidden = YES;
//            self.tabBarController.tabBar.hidden = YES;
            self.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:VC animated:YES];
            self.hidesBottomBarWhenPushed = NO;

        }
            break;
        case JUMP_CAR_SHOP:{
            
            MedicalViewController *VC = [[MedicalViewController alloc] init];
            VC.VCType = CarShopVC;
            VC.urlId = info.ids;
            self.navigationController.navigationBar.hidden = YES;
//            self.tabBarController.tabBar.hidden = YES;
            self.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:VC animated:YES];
            self.hidesBottomBarWhenPushed = NO;

        }
            break;
        case JUMP_SHOPPING_MALL:{
            
            homeNextViewController *VC=[[homeNextViewController alloc]init];

            self.hidesBottomBarWhenPushed = YES;
            VC.userID = info.ids;

            [self.navigationController pushViewController:VC animated:YES];
            self.hidesBottomBarWhenPushed = NO;
            
        }
            
            break;
        case JUMP_MEDICAL:{
            
            MedicalViewController *VC = [[MedicalViewController alloc] init];
            VC.VCType = MedicalVC;
            VC.urlId = info.ids;
            self.navigationController.navigationBar.hidden = YES;
//            self.tabBarController.tabBar.hidden = YES;
            self.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:VC animated:YES];
            self.hidesBottomBarWhenPushed = NO;

        }
            
            break;
        default:
            break;
    }

}

#pragma mark 点击大头针的协议代理
- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view{
    
//    if ([view.annotation.title isEqualToString:@"当前位置"]) {
//        return;
//    }
//    
//    __block CustomAnnotationView *weakView = view;
//    __weak typeof(self) weakSelf = self;
//    switch ([self.model.date[[view.annotation title].intValue] annotationType]) {
//        case TYPE_ENTERPRISE:{
//            
//            [self PathWithStringID:[weakSelf.model.date[[view.annotation title].intValue] ids] block:^(BubbleModel *model) {
//                weakView.xiangMu_title = model.bname;
//                weakView.PM = model.input;
//                
//                weakView.AirString = model.output;
//                
//                weakView.imageURL = model.logo;
//                
//                weakView.discountzhiURL = model.going;
//                
//                ((Infos *)weakSelf.model.date[[weakView.annotation title].intValue]).jumpType = model.type.intValue;
//                weakView.bussines=model.number;
//            }];
//            
//            return;
//        }
//        default:
//            
//            break;
//    }
    
    /* Adjust the map center in order to show the callout view completely. */
    if ([view isKindOfClass:[CACustomAnnotationView class]]) {
        CACustomAnnotationView *cusView = (CACustomAnnotationView *)view;
        CGRect frame = [cusView convertRect:cusView.calloutView.frame toView:_mapView];
        
        frame = UIEdgeInsetsInsetRect(frame, UIEdgeInsetsMake(kCalloutViewMargin, kCalloutViewMargin, kCalloutViewMargin, kCalloutViewMargin));
        
        if (!CGRectContainsRect(_mapView.frame, frame))
        {
            /* Calculate the offset to make the callout view show up. */
            CGSize offset = [self offsetToContainRect:frame inRect:_mapView.frame];
            
            CGPoint theCenter = _mapView.center;
            theCenter = CGPointMake(theCenter.x - offset.width, theCenter.y - offset.height);
            
            CLLocationCoordinate2D coordinate = [_mapView convertPoint:theCenter toCoordinateFromView:_mapView];
            
            [_mapView setCenterCoordinate:coordinate animated:YES];
        }
        
    }
    
}

- (CGSize)offsetToContainRect:(CGRect)innerRect inRect:(CGRect)outerRect
{
    CGFloat nudgeRight = fmaxf(0, CGRectGetMinX(outerRect) - (CGRectGetMinX(innerRect)));
    CGFloat nudgeLeft = fminf(0, CGRectGetMaxX(outerRect) - (CGRectGetMaxX(innerRect)));
    CGFloat nudgeTop = fmaxf(0, CGRectGetMinY(outerRect) - (CGRectGetMinY(innerRect)));
    CGFloat nudgeBottom = fminf(0, CGRectGetMaxY(outerRect) - (CGRectGetMaxY(innerRect)));
    return CGSizeMake(nudgeLeft ?: nudgeRight, nudgeTop ?: nudgeBottom);
}

#pragma mark ******************** 定位

#pragma mark -- 设置定位按钮
- (void)initControls
{
    _locationButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _locationButton.frame = CGRectMake(20, CGRectGetHeight(_mapView.bounds) - 110, 45, 45);
    _locationButton.autoresizingMask = UIViewAutoresizingFlexibleRightMargin |
    UIViewAutoresizingFlexibleTopMargin;
    _locationButton.layer.cornerRadius = 1;
    [_locationButton addTarget:self action:@selector(locateAction)
              forControlEvents:UIControlEventTouchUpInside];
    
    [_locationButton setImage:[UIImage imageNamed:@"地图指标"].originalImage forState:UIControlStateNormal];
    [_mapView addSubview:_locationButton];
}

- (void)locateAction// 点击定位按钮 回到地图中心
{
    if (_mapView.userTrackingMode != MAUserTrackingModeFollow)
    {
        [_mapView setUserTrackingMode:MAUserTrackingModeFollow animated:YES];
    }
}

#pragma mark -- 定位回调 & 地理编码
-(void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation
updatingLocation:(BOOL)updatingLocation
{
    if(updatingLocation)
    {
        //取出当前位置的坐标
//        NSLog(@"latitude : %f,longitude: %f",userLocation.coordinate.latitude,userLocation.coordinate.longitude);
        
        loginmodel.jingDu = [NSString stringWithFormat:@"%f",userLocation.coordinate.latitude]    ;
        loginmodel.weiDu =[NSString stringWithFormat:@"%f",userLocation.coordinate.longitude]    ;
        
        //构造AMapReGeocodeSearchRequest对象
        AMapReGeocodeSearchRequest *regeo = [[AMapReGeocodeSearchRequest alloc] init];
        regeo.location = [AMapGeoPoint locationWithLatitude:userLocation.coordinate.latitude  longitude:userLocation.coordinate.longitude];
        regeo.radius = 10000;
        regeo.requireExtension = NO;
        
        //发起逆地理编码
        [_search AMapReGoecodeSearch: regeo];
        
    }
}


//实现逆地理编码的回调函数
- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response
{
    if(response.regeocode != nil)
    {
        //通过AMapReGeocodeSearchResponse对象处理搜索结果
        
        //如果滚动条没有加载 就证明没有区请求数据
        if (rollViewLabel == nil) {
            //拿到结果去请求天气
            [self getWeatherInfoWithCityName:response.regeocode.addressComponent.province];
        }
        
        //判断两次定位的区是否一样如果不一样那就是进入了另一个区
        if(![[LoginSingleton sharedLoginSingleton].searchBaseRequest.regeocode.addressComponent.district isEqualToString:response.regeocode.addressComponent.district]){
            
            [LoginSingleton sharedLoginSingleton].searchBaseRequest = response;
            
        }
    }
}


#pragma mark -- 定位时改变图标的样式
- (void)mapView:(MAMapView *)mapView didChangeUserTrackingMode:(MAUserTrackingMode)mode animated:(BOOL)animated
{
    if (mode==MAUserTrackingModeNone) {
        [_locationButton setImage:[UIImage imageNamed:@"地图指标"] forState:UIControlStateNormal];
    }else{
        
        
        [_locationButton setImage:[UIImage imageNamed:@"地图指标-拷贝"] forState:UIControlStateNormal];
    }
    
}




#pragma mark ******************** 给地图添加色块

- (NSMutableArray *)overlayArray{
    if (_overlayArray == nil) {
        _overlayArray = [NSMutableArray new];
    }
    return _overlayArray;
}

//地图分区显示不同的颜色
- (UIColor *)checkColorWithNumber:(NSString *)aNum{
    float a = aNum.floatValue;
    
    UIColor *color;
    if(0 < a && a <= 50){
        color = [UIColor colorWithRed:0.39 green:0.847 blue:0.25 alpha:1];
    }else if(50 < a && a <= 100){
        color = [UIColor colorWithRed:0.98 green:0.913 blue:0.294 alpha:1];
    }else if(100 < a && a <= 150){
        color = [UIColor colorWithRed:0.937 green:0.525 blue:0.2 alpha:1];
    }else if(150 < a && a <= 200){
        color = [UIColor colorWithRed:0.917 green:0.2 blue:0.137 alpha:1];
    }else if(200 < a && a <= 250){
        color = [UIColor colorWithRed:0.458 green:0.094 blue:0.486 alpha:1];
    }else{
        color = [UIColor colorWithRed:0.356 green:0.05 blue:0.03 alpha:1];
    }
    
    return color;
}


//添加色块
- (void)divideTheArea{
    
//    [self updateCityDic];//更新字典
    
    //移除分区颜色块
    [_mapView removeOverlays:self.overlayArray];
    
    //清楚颜色块数组
    [self.overlayArray removeAllObjects];
    
    for (int i = 0; i < self.partitionColorAry.count; i++){
        
        PartitionColor *model = self.partitionColorAry[i];
        
        for (NSString *locationStr in [model polyoines]) {
             CLLocationCoordinate2D coordinates[10000];
            
            NSArray *tempLocationAry = [locationStr componentsSeparatedByString:@";"];
            
            for ( int j = 0; j < tempLocationAry.count; j++) {
                
                NSArray *locationXYAry = [tempLocationAry[j] componentsSeparatedByString:@","];
                
                coordinates[j] = (CLLocationCoordinate2D){[locationXYAry[1] doubleValue],[locationXYAry[0] doubleValue]};
                
            }
            
            MAPolygon *pol = [MAPolygon polygonWithCoordinates:coordinates count:tempLocationAry.count];
            pol.title = [NSString stringWithFormat:@"%d",i];
            //添加颜色块数组
            [self.overlayArray addObject:pol];
            
        }
    
    }
    //地图上添加颜色块
    [_mapView addOverlays:self.overlayArray];
    
}

#pragma mark - MAMapViewDelegate

- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay
{
    if ([overlay isKindOfClass:[MAGroundOverlay class]])
    {
        MAGroundOverlayRenderer *groundOverlayRenderer = [[MAGroundOverlayRenderer alloc] initWithGroundOverlay:overlay];
        [groundOverlayRenderer setAlpha:0.6];
        
        return groundOverlayRenderer;
    }else if ([overlay isKindOfClass:[MAPolygon class]])
    {
        MAPolygonRenderer *polygonRenderer = [[MAPolygonRenderer alloc] initWithPolygon:overlay];
//        polygonRenderer.lineWidth   = 0.0f;
//        polygonRenderer.strokeColor = [UIColor clearColor];//[UIColor colorWithRed:0 green:1 blue:0 alpha:1];
        polygonRenderer.alpha = 0.4;
         
        polygonRenderer.fillColor = [self checkColorWithNumber:[self.partitionColorAry[overlay.title.integerValue] aqi]];
        
        return polygonRenderer;
    }
     
    return nil;
}

#pragma mark -- 初始化城市分区字典 （色块弟子安）

- (void)initCityDic{
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"city" ofType:@"plist"];
    NSArray *cAry = [NSMutableArray arrayWithContentsOfFile:path];
    
    for (NSDictionary *pro in cAry) {
        for (NSDictionary *city in pro[@"province_districts"]) {
            for(NSDictionary *dis in city[@"city_districts"]){
                
                PartitionColor *col = [[PartitionColor alloc] init];
                [col setValuesForKeysWithDictionary:pro];
                [col setValuesForKeysWithDictionary:city];
                [col setValuesForKeysWithDictionary:dis];
                
                [self.partitionColorAry addObject:col];
                
            }
        }
    }
    
}

#pragma mark -- 请求数据后更新 城市分区字典中的颜色

- (void)updateCityDic{
    
    
}

#pragma mark ******************** 网络请求

#pragma mark -- 网络请求 获取滚动条
- (void)getWeatherInfoWithCityName:(NSString *)city{
    
    __weak __typeof(self) weakSelf = self;
    [HTTPManager get:[[NSString stringWithFormat:@"%@/Api/Dervice/getMsgWeather?province=%@",urlHeader,city] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding] success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        if (responseObject != nil) {
            
            WeatherModel *model = [[WeatherModel alloc] init];
            [model setValuesForKeysWithDictionary:responseObject[@"date"]];
            
            weatherModel = model;
            
            [weakSelf initRollText];
        }
        
    }];
    
    
}

#pragma mark -- 网络请求 获取地图分区颜色
- (void)getPartitionColor{
    
    __weak __typeof(self) weakSelf = self;
    [HTTPManager get:[NSString stringWithFormat:@"%@/Api/Dervice/getAirPot",urlHeader] success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        if ([responseObject[@"code"] isEqualToString:@"0000"]) {
    

            for (NSDictionary *pro in responseObject[@"date"]) {
                
                for (NSDictionary *city in pro[@"pro"]) {
                    
                    for (NSDictionary *area in city[@"air"]) {

                        for (int i = 0; i < self.partitionColorAry.count; i++) {
                            
                            if ([area[@"area_code"] isEqualToString:[self.partitionColorAry[i] district_adcode]]) {
                                
                                ((PartitionColor *)self.partitionColorAry[i]).aqi = area[@"aqi"];
                                ((PartitionColor *)self.partitionColorAry[i]).aqi_garde_lv = area[@"aqi_garde_lv"];
                                
                            }
                            
                        }
                    }
                }
            }
            
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                [weakSelf divideTheArea];
            });
            
        }
        
    }];
    
}


#pragma mark -- 网络请求 获取地图大头针信息
- (void)getMapPinsInfo{
    
    [HTTPManager get:[NSString stringWithFormat:@"%@/Api/Dervice/list",urlHeader] success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        if ([responseObject[@"code"] isEqualToString:@"0000"]) {
            
            self.model = [[MapPinsModel alloc] init];
            [self.model setValuesForKeysWithDictionary:responseObject];
            [self initMApointAnnotation:TYPE_ALL];
            
        } 
        
    }];
    
}

#pragma mark -- 气泡请求数据
-(void)PathWithStringID:(NSString*)ID block:(void(^)( BubbleModel*model))block{
  

    BubbleModel *model=[[BubbleModel alloc]init];
    
    [HTTPManager get:[NSString stringWithFormat:@"http://cleanerair.com.cn/Api/Dervice/getPM?id=%@",ID] success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        if ([responseObject[@"code"] isEqualToString:@"0000"]) {
            
            NSDictionary*dic=[responseObject objectForKey:@"date"];
            [model setValuesForKeysWithDictionary:dic];
            
            block(model);
            
        }
     
    }]; 

}


#pragma mark ******************** 色块说明

#pragma mark ----- 添加右边颜色条 和 问号

- (void)initColorArticle{
    
    UIImageView *colorArticle = [[UIImageView alloc] initWithFrame:CGRectMake(MAIN_WIDTH - 40, MAIN_HEIGHT - 44 - 280, 30, 180)];
    colorArticle.image = [UIImage imageNamed:@"数值.png"];
    colorArticle.alpha = 0.8;
    colorArticle.userInteractionEnabled = YES;
    [colorArticle addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addQuestView)]];
    
    
    self.question = [[UIImageView alloc] initWithFrame:CGRectMake(colorArticle.frame.origin.x + 18 , CGRectGetMaxY(colorArticle.frame) + 5, 15, 15)];
    self.question.image = [UIImage imageNamed:@"小黑问号.png"];
    self.question.alpha = 0.8;
    self.question.userInteractionEnabled = YES;
    [self.question addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addQuestView)]];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [self.view addSubview:colorArticle];
        [self.view addSubview:self.question];
        
    });
    
}

#pragma mark -- 初始化问号view
- (UIView *)questView{
    if (_questView == nil) {
        
        CGFloat H = MAIN_HEIGHT * 0.7;
        CGFloat W = MAIN_WIDTH * 0.7;
        
        _questView = [[UIView alloc] initWithFrame:(CGRectMake(0, 0, W, H))];
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:(CGRectMake(0, 0, W, H))];
        imageView.image = [UIImage imageNamed:@"等级.png"];
        _questView.center = CGPointMake(self.view.center.x , self.view.center.y - 85);
        [_questView addSubview:imageView];
    }
    return _questView;
}

#pragma mark -- 弹出颜色说明页面

- (void)addQuestView{
    
    if (self.questView.superview == nil) {
        
        [self.view addSubview:_questView];
        
        //        CGAffineTransform newTransform = CGAffineTransformMakeScale(1.2, 1.2);
        //        [_questView setTransform:newTransform];
        
        [UIView animateWithDuration:0.1 animations:^{
            CGAffineTransform newTransform = CGAffineTransformMakeScale(1.1, 1.1);
            [_questView setTransform:newTransform];
        }completion:^(BOOL finished){
            [UIView animateWithDuration:0.1 animations:^{
                CGAffineTransform newTransform = CGAffineTransformMakeScale(0.9, 0.9);
                [_questView setTransform:newTransform];
            } completion:^(BOOL finished){
                [UIView animateWithDuration:0.1 animations:^{
                    CGAffineTransform newTransform = CGAffineTransformMakeScale(1.0, 1.0);
                    [_questView setTransform:newTransform];
                } completion:^(BOOL finished){
                    
                }];
            }];
        }];
    }else{
        
        [self removeQuestViewForFaterView];
        
    }
    
}

#pragma mark --- 移除颜色说明页面
- (void)removeQuestViewForFaterView{
    
    [_questView removeFromSuperview];
    
}

#pragma mark --- 给Viewcontroller添加移除颜色说明方法

- (void)addGestureRecognizer{
    
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removeQuestViewForFaterView)];
    //设置成NO表示当前控件响应后会传播到其他控件上，默认为YES。
    tapGestureRecognizer.cancelsTouchesInView = NO;
    //将触摸事件添加到当前view
    
    [self.view addGestureRecognizer:tapGestureRecognizer];
    
}

- (NSMutableArray *)datarr{
    if (_datarr == nil) {
        _datarr=[[NSMutableArray alloc]init];
    }
    return _datarr;
}

@end
